package com.bmf.module.testQuestions.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bmf.module.testQuestions.entity.QuestionType;
import com.bmf.module.testQuestions.mapper.QuestionTypeMapper;
import com.bmf.module.testQuestions.service.QuestionTypeService;
import com.bmf.module.testQuestions.vo.QuestionTypeCreateVo;
import com.bmf.module.testQuestions.vo.TypeResultVo;
import com.bmf.utils.BeanCopyUtils;
import com.bmf.utils.SecurityUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * (QuestionType)表服务实现类
 *
 * @author makejava
 * @since 2022-11-30 14:20:48
 */
@Service("questionTypeService")
public class QuestionTypeServiceImpl extends ServiceImpl<QuestionTypeMapper, QuestionType> implements QuestionTypeService {

    @Override
    public List<TypeResultVo> selectAll() {
        LambdaQueryWrapper<QuestionType> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(QuestionType::getCreateId, SecurityUtils.getUserId());
        List<QuestionType> list = list(wrapper);
        if(CollUtil.isNotEmpty(list)){
            List<TypeResultVo> typeResultVos = BeanCopyUtils.copyBeanList(list, TypeResultVo.class);
            return typeResultVos.stream().filter(s -> s.getParentId() == 0).peek(s -> setChildren(typeResultVos, s)).collect(Collectors.toList());
        }
        return null;
    }
    private void setChildren(List<TypeResultVo> typeResultVos,TypeResultVo typeResultVo){
        List<TypeResultVo> childrens = typeResultVos.stream().filter(s -> s.getParentId() == typeResultVo.getId()).peek(s -> setChildren(typeResultVos, s))
                .collect(Collectors.toList());
        typeResultVo.setChildrens(childrens);
    }

    @Override
    public Integer insert(QuestionTypeCreateVo questionTypeCreateVo) {
        QuestionType questionType = BeanCopyUtils.copyBean(questionTypeCreateVo, QuestionType.class);
        questionType.setCreateId(SecurityUtils.getUserId());
        save(questionType);
        return questionType.getId();
    }
}
